<template>
  <div class="region-list-page">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="text-base font-medium">区域维护</div>
          <div class="space-x-2">
            <el-button
              type="primary"
              :icon="useRenderIcon('ep:plus')"
              @click="openCreateRoot"
            >
              新增顶级区域
            </el-button>
            <el-button
              :icon="useRenderIcon('ep:refresh')"
              :loading="loading"
              @click="loadRegionTree"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>
      <div class="flex gap-6">
        <div
          class="w-1/2 border border-dashed border-gray-200 rounded-md p-4 h-[520px]"
        >
          <el-scrollbar class="h-full">
            <el-tree
              ref="treeRef"
              :data="regionTree"
              node-key="id"
              highlight-current
              default-expand-all
              :props="treeProps"
              @node-click="handleNodeClick"
            >
              <template #default="{ data }">
                <div class="flex items-center justify-between w-full pr-2">
                  <div class="flex items-center gap-2">
                    <span class="font-medium">{{ data.name }}</span>
                    <el-tag
                      size="small"
                      effect="plain"
                      :type="data.status === 1 ? 'success' : 'danger'"
                    >
                      {{ data.status === 1 ? "启用" : "停用" }}
                    </el-tag>
                    <el-tag
                      v-if="data.code"
                      size="small"
                      type="info"
                      effect="plain"
                    >
                      {{ data.code }}
                    </el-tag>
                    <el-tag
                      v-if="data.level === 1"
                      size="small"
                      type="warning"
                      effect="plain"
                    >
                      卖家 {{ data.seller_count ?? 0 }}
                    </el-tag>
                    <el-tag
                      v-if="data.level === 1"
                      size="small"
                      type="success"
                      effect="plain"
                    >
                      买家 {{ data.buyer_count ?? 0 }}
                    </el-tag>
                  </div>
                  <div class="flex items-center gap-2">
                    <el-button
                      link
                      type="primary"
                      size="small"
                      :icon="useRenderIcon('ep:plus')"
                      @click.stop="openCreateChild(data)"
                    >
                      新增
                    </el-button>
                    <el-button
                      link
                      type="default"
                      size="small"
                      :icon="useRenderIcon('ep:edit')"
                      @click.stop="openEdit(data)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      link
                      type="danger"
                      size="small"
                      :icon="useRenderIcon('ep:delete')"
                      @click.stop="removeRegion(data)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
        <div class="flex-1">
          <el-card v-if="currentRegion" shadow="hover">
            <template #header>
              <div class="flex items-center justify-between">
                <div class="text-base font-medium">
                  区域详情 - {{ currentRegion.name }} (ID:
                  {{ currentRegion.id }})
                </div>
                <div class="space-x-2">
                  <el-button
                    type="primary"
                    :icon="useRenderIcon('ep:plus')"
                    @click="openCreateChild(currentRegion)"
                  >
                    新增子区域
                  </el-button>
                  <el-button
                    :icon="useRenderIcon('ep:edit')"
                    @click="openEdit(currentRegion)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    :icon="useRenderIcon('ep:delete')"
                    @click="removeRegion(currentRegion)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </template>
            <el-descriptions :column="1" border label-class-name="w-32">
              <el-descriptions-item label="区域名称">
                {{ currentRegion.name }}
              </el-descriptions-item>
              <el-descriptions-item label="区域编码">
                {{ currentRegion.code || "—" }}
              </el-descriptions-item>
              <el-descriptions-item label="层级">
                第 {{ currentRegion.level ?? 1 }} 层
              </el-descriptions-item>
              <el-descriptions-item label="排序值">
                {{ currentRegion.sort ?? 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag
                  :type="currentRegion.status === 1 ? 'success' : 'danger'"
                >
                  {{ currentRegion.status === 1 ? "启用" : "停用" }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item
                v-if="currentRegion.level === 1"
                label="客户统计"
              >
                <div class="flex flex-wrap gap-4 text-sm text-gray-600">
                  <span>卖家：{{ currentRegion.seller_count ?? 0 }}</span>
                  <span>买家：{{ currentRegion.buyer_count ?? 0 }}</span>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="父级区域">
                {{ parentName(currentRegion.parent_id) }}
              </el-descriptions-item>
              <el-descriptions-item label="关联时间">
                <div class="space-y-1 text-sm text-gray-500">
                  <div>创建：{{ currentRegion.create_time ?? "—" }}</div>
                  <div>更新：{{ currentRegion.update_time ?? "—" }}</div>
                </div>
              </el-descriptions-item>
            </el-descriptions>

            <template v-if="currentChildren.length">
              <el-divider />
              <div class="flex items-center justify-between mb-3">
                <div class="text-sm font-medium text-gray-700">
                  下属省份（{{ currentChildren.length }}）
                </div>
              </div>
              <el-table
                :data="currentChildren"
                size="small"
                border
                class="child-table"
              >
                <el-table-column prop="name" label="省份名称" min-width="160" />
                <el-table-column
                  prop="code"
                  label="编码"
                  min-width="120"
                  show-overflow-tooltip
                />
                <el-table-column prop="sort" label="排序" width="80" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag
                      :type="row.status === 1 ? 'success' : 'danger'"
                      effect="plain"
                      size="small"
                    >
                      {{ row.status === 1 ? "启用" : "停用" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                  <template #default="{ row }">
                    <el-button
                      link
                      type="primary"
                      size="small"
                      :icon="useRenderIcon('ep:edit')"
                      @click="openEditChild(row)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      link
                      type="danger"
                      size="small"
                      :icon="useRenderIcon('ep:delete')"
                      @click="removeChild(row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-card>
          <el-empty v-else description="请选择左侧区域" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { fetchRegionTree, deleteRegion } from "@/api/system/region/region";
import RegionForm from "./components/RegionForm.vue";
import { useDialog } from "@/composables/useDialog";

interface RegionTreeNode {
  id: number;
  name: string;
  code?: string;
  parent_id?: number;
  level?: number;
  sort?: number;
  status?: number;
  seller_count?: number;
  buyer_count?: number;
  create_time?: string;
  update_time?: string;
  children?: RegionTreeNode[];
}

const treeProps = {
  label: "name",
  children: "children"
};

const treeRef = ref();
const { openDialog } = useDialog();
const regionTree = ref<RegionTreeNode[]>([]);
const allRegions = ref<RegionTreeNode[]>([]);
const currentRegion = ref<RegionTreeNode | null>(null);
const loading = ref(false);

const flatRegions = computed(() => {
  const result: RegionTreeNode[] = [];
  const dfs = (nodes: RegionTreeNode[]) => {
    nodes.forEach(node => {
      result.push(node);
      if (Array.isArray(node.children) && node.children.length) {
        dfs(node.children);
      }
    });
  };
  dfs(allRegions.value);
  return result;
});

const parentName = (parentId?: number) => {
  if (!parentId) return "无";
  const parent = flatRegions.value.find(item => item.id === parentId);
  return parent ? `${parent.name} (ID:${parent.id})` : "—";
};

const loadRegionTree = async () => {
  loading.value = true;
  try {
    const tree = await fetchRegionTree();
    allRegions.value = tree;
    const topLevel = tree.filter(item => (item.level ?? 1) === 1);
    regionTree.value = topLevel;
    const fallbackSource = topLevel.length ? topLevel : tree;
    if (fallbackSource.length) {
      if (!currentRegion.value) {
        currentRegion.value = fallbackSource[0];
      } else {
        const found = fallbackSource.find(
          item => item.id === currentRegion.value?.id
        );
        currentRegion.value = found ?? fallbackSource[0];
      }
    } else {
      currentRegion.value = null;
    }
  } catch (error: any) {
    ElMessage.error(error?.message ?? "加载区域失败");
  } finally {
    loading.value = false;
  }
};

const handleNodeClick = (node: RegionTreeNode) => {
  currentRegion.value = node;
};

const openCreateRoot = () => {
  openRegionDialog({ mode: "create", parent: null });
};

const openCreateChild = (parent: RegionTreeNode) => {
  if ((parent.level ?? 1) >= 2) {
    ElMessage.error("当前仅支持两级区域结构");
    return;
  }
  openRegionDialog({ mode: "create", parent });
};

const openEdit = (region: RegionTreeNode) => {
  openRegionDialog({
    mode: "edit",
    region,
    parent: getParent(region.parent_id)
  });
};

const getParent = (parentId?: number) => {
  if (!parentId) return null;
  return flatRegions.value.find(item => item.id === parentId) ?? null;
};

const openRegionDialog = ({
  mode,
  region,
  parent
}: {
  mode: "create" | "edit";
  region?: RegionTreeNode | null;
  parent?: RegionTreeNode | null;
}) => {
  openDialog(RegionForm, {
    title: mode === "create" ? "新增区域" : `编辑区域 - ${region?.name}`,
    width: "480px",
    props: {
      mode,
      region,
      parentRegion:
        parent ?? (region?.parent_id ? getParent(region?.parent_id) : null)
    },
    onConfirm: async (_: any, dialogProxy: any) => {
      if (dialogProxy?.submitForm) {
        const ok = await dialogProxy.submitForm();
        if (ok) {
          await loadRegionTree();
        }
        return ok;
      }
      return true;
    }
  });
};

const removeRegion = async (region: RegionTreeNode) => {
  try {
    await ElMessageBox.confirm(
      `确认删除区域 “${region.name}” 吗？该操作不可恢复。`,
      "删除区域",
      {
        type: "warning",
        confirmButtonText: "删除",
        cancelButtonText: "取消"
      }
    );
  } catch {
    return;
  }

  try {
    await deleteRegion(region.id);
    ElMessage.success("区域已删除");
    if (currentRegion.value?.id === region.id) {
      currentRegion.value = null;
    }
    await loadRegionTree();
  } catch (error: any) {
    ElMessage.error(error?.message ?? "删除失败");
  }
};

const currentChildren = computed(() => {
  if (!currentRegion.value) return [];
  return flatRegions.value.filter(
    item => item.parent_id === currentRegion.value?.id
  );
});

const openEditChild = (child: RegionTreeNode) => {
  openRegionDialog({
    mode: "edit",
    region: child,
    parent: getParent(child.parent_id)
  });
};

const removeChild = async (child: RegionTreeNode) => {
  await removeRegion(child);
};

loadRegionTree();
</script>

<style scoped>
.region-list-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.region-list-page :deep(.el-tree-node__content) {
  padding-right: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.region-list-page :deep(.el-tree-node__content:hover) {
  background-color: rgba(64, 158, 255, 0.08);
}

.child-table {
  margin-top: 8px;
}
</style>
